﻿using Simple.Tools.File;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Net;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading.Tasks;

namespace Simple.Tools
{
	/// <summary>
	/// 
	/// </summary>
	public static class SimpleCheck
	{
        static SimpleCheck()
		{
				Wwwroot = "wwwroot";
				Dot = '.';
				Colon = ':';
				Sprit = '/';
				UnSprit = '\\';
            }
		/// <summary>
		/// 是否为空字符串
		/// </summary>
		/// <param name="value"></param>
		/// <returns></returns>
		public static bool IsNullOrEmpty(string value)
		{
			return string.IsNullOrEmpty(value);
		}

		/// <summary>
		/// 是否为空字符串
		/// </summary>
		/// <param name="value"></param>
		/// <returns></returns>
		public static bool IsNotNullOrEmpty(string value)
		{
			return string.IsNullOrEmpty(value)==false;
		}
		/// <summary>
		/// 集合是否为空
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="array"></param>
		/// <returns></returns>
		public static bool IsNullOrEmpty<T>(IEnumerable<T> array)
		{
			return array == null || array.Count() == 0;
		}

		/// <summary>
		/// 集合是否为空
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="array"></param>
		/// <returns></returns>
		public static bool IsNotNullOrEmpty<T>(IEnumerable<T> array)
		{
			return IsNullOrEmpty(array)==false;
		}
		/// <summary>
		/// 如果为空将抛出异常
		/// </summary>
		/// <param name="o"></param>
		/// <exception cref="ArgumentNullException"></exception>
		public static void IsNullThrowException(this object o)
		{
			if (IsNull(o))
			{
				throw new ArgumentNullException("");
			}
		}
		/// <summary>
		/// 
		/// </summary>
		/// <param name="o"></param>
		/// <param name="msg"></param>
		/// <exception cref="ArgumentNullException"></exception>
		public static void IsNullThrowException(this object o, string msg)
		{
			if (IsNull(o))
			{
				throw new ArgumentNullException(msg);
			}
		}
		/// <summary>
		/// 异常捕获
		/// </summary>
		/// <param name="action">需要捕获的内容</param>
		/// <param name="actionCatch">处理异常</param>
		/// <param name="actionFinally">最后默认执行</param>
		public static void TryCatch(Action action,Action<Exception> actionCatch=null,Action actionFinally=null)
		{
			try
			{
				if (!IsNull(action))
				{
					action.Invoke();
				}
			}
			catch (Exception ex)
			{
				if (!IsNull(actionCatch))
				{
					actionCatch.Invoke(ex);
				}
				else
				{
					throw ex;
				}
			}finally
			{
				if (!IsNull(actionFinally))
				{
					actionFinally.Invoke();
				}
			}
		}
		/// <summary>
		///  guid 是否是空
		/// </summary>
		/// <param name="o"></param>
		/// <returns></returns>
		public static Boolean IsEmpty(this Guid o)
		{
			return o == Guid.Empty;
		}

		/// <summary>
		///  guid 是否是空
		/// </summary>
		/// <param name="o"></param>
		/// <returns></returns>
		public static Boolean IsNotEmpty(this Guid o)
		{
			return o != Guid.Empty;
		}
		/// <summary>
		/// 对象是否是空值
		/// </summary>
		/// <param name="o"></param>
		/// <returns></returns>
		public static Boolean IsNull(this object o)
		{
			return o == null;
		}

		/// <summary>
		/// 对象是否是空值
		/// </summary>
		/// <param name="o"></param>
		/// <returns></returns>
		public static Boolean IsNotNull(this object o)
		{
			return o != null;
		}
		/// <summary>
		/// 如果字符串为空将放回空字符
		/// </summary>
		/// <param name="value"></param>
		/// <returns></returns>
		public static string IsNullGetEmpty(this string value)
		{
			if (IsNullOrEmpty(value))
			{
				return string.Empty;
			}
			else
			{
				return value;
			}
		}
		/// <summary>
		/// 当前平台是否是liunx
		/// </summary>
		/// <returns></returns>
		public static bool PlatformIsLinux()
		{
			return RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
		}
		/// <summary>
		/// 当前平台是否是windows
		/// </summary>
		/// <returns></returns>
		public static bool PlatformIsWindows()
		{
			return RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
		}
		/// <summary>
		/// 当前平台是否是FreeBSD
		/// </summary>
		/// <returns></returns>
		public static bool PlatformIsFreeBSD()
		{
			throw new Exception("standard2.1不支持!");
			return false;
			//return RuntimeInformation.IsOSPlatform(OSPlatform.FreeBSD);
		}
		/// <summary>
		/// 检查当前代码执行模式
		/// </summary>
		/// <returns></returns>
		public static bool IsDebug()
		{

			if (_isDebugMode == null)
			{
				var assembly = Assembly.GetEntryAssembly();
				if (assembly == null)
				{
					// 由于调用 GetFrames 的 StackTrace 实例没有跳过任何帧，所以 GetFrames() 一定不为 null。
					assembly = new StackTrace().GetFrames().Last().GetMethod().Module.Assembly;
				}

				var debuggableAttribute = assembly.GetCustomAttribute<DebuggableAttribute>();
				_isDebugMode = debuggableAttribute.DebuggingFlags
					.HasFlag(DebuggableAttribute.DebuggingModes.EnableEditAndContinue);
			}
			return _isDebugMode.Value;
		}

		private static bool? _isDebugMode;

		/// <summary>
		/// 
		/// </summary>
		public static string Wwwroot;
		#region
		/// <summary>
		/// 点号
		/// </summary>
		public static char Dot;
		/// <summary>
		/// 分号
		/// </summary>
		public static char Colon;
		/// <summary>
		/// 斜杠
		/// </summary>
		public static char Sprit;
		/// <summary>
		/// 反斜杠
		/// </summary>
		public static char UnSprit;
		#endregion

		/// <summary>
		///  是否是当前类型的子类型
		/// </summary>
		/// <param name="parentType"></param>
		/// <param name="childType"></param>
		/// <returns></returns>
		public static bool IsChild(this Type parentType,Type childType)
		{
			if (parentType==null || childType==null)
			{
				return false;
			}
			return parentType.IsAssignableFrom(childType);
		}

		/// <summary>
		///  是否是当前类型的父类型
		/// </summary>
		/// <param name="childType"></param>
		/// <param name="parentType"></param>
		/// <returns></returns>
		public static bool IsParent(this Type childType, Type parentType)
        {
            return parentType.IsChild(childType);
        }

		/// <summary>
		/// 文件是否存在
		/// </summary>
		/// <param name="path"></param>
		/// <returns></returns>
		public static bool FileExists(string path)
		{
			if (IsNullOrEmpty(path))
			{
				return false;
			}
			return System.IO.File.Exists(path);
			
        }

		/// <summary>
		/// 读取文件中内容
		/// </summary>
		/// <param name="path"></param>
		/// <returns></returns>
        public static string ReadAllText(string path)
        {
			if (!FileExists(path))
			{
				path = System.IO.Path.Combine(AppContext.BaseDirectory,path);

				if (!FileExists(path))
				{
					throw new Exception("文件不存在!");
				}
            }
            return System.IO.File.ReadAllText(path);
        }

		/// <summary>
		/// 如果文件不存在就创建文件 创建完成之后会做一定的延迟
		/// </summary>
		/// <param name="FilePath"></param>
		public static void CreateFile(string FilePath)
		{
			if (!System.IO.File.Exists(FilePath))
			{
				if (!FilePath.Contains(AppDomain.CurrentDomain.BaseDirectory))
				{
					FilePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, FilePath);
				}
				if (!Directory.Exists(Path.GetDirectoryName(FilePath)))
				{
					Directory.CreateDirectory(Path.GetDirectoryName(FilePath));
				}
				System.IO.File.Create(FilePath);
				Task.Delay(300).Wait();
			}
		}

		/// <summary>
		/// 获取本机默认IP
		/// </summary>
		/// <returns></returns>
		public static IPAddress GetLocalHostFirstOrDefault()
		{
			try
			{
				//NetworkInterface：提供网络接口的配置和统计信息。
				NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
				foreach (NetworkInterface adapter in adapters)
				{
					IPInterfaceProperties adapterProperties = adapter.GetIPProperties();
					UnicastIPAddressInformationCollection allAddress = adapterProperties.UnicastAddresses;
					//这里是根据网络适配器名称找到对应的网络，adapter.Name即网络适配器的名称

					foreach (UnicastIPAddressInformation addr in allAddress)
					{
						if (addr.Address.AddressFamily == AddressFamily.InterNetwork && addr.DuplicateAddressDetectionState == DuplicateAddressDetectionState.Preferred)
						{
							return addr.Address;
						}
					}
				}
			}
			catch (Exception ex)
			{
			}
			finally
			{
			}
			IPAddress.TryParse("127.0.0.1", out IPAddress ipaddress);
			return ipaddress;

		}

		/// <summary>
		/// 获取本机可用ip集合
		/// </summary>
		/// <returns></returns>
		public static IList<string> GetLocalHosts()
		{
			IList<string> strIp = new List<string>();
			try
			{
				//NetworkInterface：提供网络接口的配置和统计信息。
				NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
				foreach (NetworkInterface adapter in adapters)
				{
					IPInterfaceProperties adapterProperties = adapter.GetIPProperties();
					UnicastIPAddressInformationCollection allAddress = adapterProperties.UnicastAddresses;
					//这里是根据网络适配器名称找到对应的网络，adapter.Name即网络适配器的名称

					foreach (UnicastIPAddressInformation addr in allAddress)
					{
						if (addr.Address.AddressFamily == AddressFamily.InterNetwork)
						{
							strIp.Add(addr.Address.ToString());
						}
					}
				}
			}
			catch (Exception ex)
			{
			}
			finally
			{
			}
			return strIp;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="cmd"></param>
		/// <returns></returns>
		public static string Bash(this string cmd)
		{
			string result = String.Empty;

			try
			{
				var escapedArgs = cmd.Replace("\"", "\\\"");

				using (Process process = new Process())
				{
					process.StartInfo = new ProcessStartInfo
					{
						FileName = "/bin/bash",
						Arguments = $"-c \"{escapedArgs}\"",
						RedirectStandardOutput = true,
						UseShellExecute = false,
						CreateNoWindow = true,
					};

					process.Start();
					result = process.StandardOutput.ReadToEnd();
					process.WaitForExit(1500);
					process.Kill();
				};
			}
			catch (Exception ex)
			{
				//Logger.ErrorFormat(ex.Message, ex);
			}
			return result;
		}


	}
}